import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:search_people/page/home/main/logic.dart';
import 'package:search_people/page/home/main/state.dart';
import 'package:search_people/utils/storage.dart';
import 'package:search_people/utils/util.dart';
import 'package:search_people/value/topcolors.dart';

import '../../../../entrance/route/routes.dart';
import '../../../../utils/component/component.dart';
import 'index.dart';

class MenuAllController extends GetxController {
  MenuAllController();

  final state = MenuAllState();
  final homeCtrl = Get.find<HomeLogic>();

  void actionDelete({
    required MenuAllModel md,
    required int idx,
  }) {
    md.items.removeAt(idx);
    update();
  }

  void actionEdit() {
    if (!state.isEditing) {
      var recents = state.items.first.items;
      var str = recents.map((e) => e.idx!.toString()).join(',');
      SpUtil().setStr(StorageKeys.recent_menu, str);
    }
    update();
  }

  void setupRecentMenus() {
    String str = SpUtil().getStr(StorageKeys.recent_menu);
    var list = str.split(',');
    if (list.isEmpty) {
      return;
    }
    var items = list
        .map((e) => HomeMenuType.init(numVal(e).toInt()))
        .map((v) => MenuItem()
          ..title = v.title
          ..icon = v.icon
          ..idx = v.val
          ..onTap = () {
            homeCtrl.actionMenuItem(v);
          })
        .toList();
    var md = MenuAllModel(
      title: '最近使用',
      items: items,
      icon: IconUtil.menu_recent,
      iconColor: const Color(0xffF4A460),
      isCanDelete: true,
    );
    state.items.insert(0, md);
  }

  void setupSearchMenus() {
    var md = MenuAllModel(
        title: '综合查询',
        items: HomeMenuType.searchItems
            .map((e) => MenuItem()
              ..title = e.title
              ..icon = e.icon
              ..onTap = () {
                homeCtrl.actionMenuItem(e);
              })
            .toList(),
        icon: IconUtil.menu_search,
        iconColor: const Color(0xff3CB371));
    state.items.add(md);
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.items = [];
    setupRecentMenus();
    setupSearchMenus();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
